﻿using Microsoft.SemanticKernel.Connectors.AI.OpenAI;
using Microsoft.SemanticKernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using System.Text.Json;
using Microsoft.SemanticKernel.Planners;

namespace SemanticKernelDemo
{
    internal class PlannerDemo
    {
        public static async Task<string> Run()
        {
            var builder = new KernelBuilder();

            var (useAzureOpenAI, model, azureEndpoint, apiKey, orgId) = Settings.LoadFromFile();

            var pluginsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "samples", "plugins");
           
            builder.WithOpenAIChatCompletionService(model, apiKey, orgId);
            var kernel = builder.Build();

            var planner = new SequentialPlanner(kernel);
            kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, "SummarizePlugin");
            kernel.ImportSemanticFunctionsFromDirectory(pluginsDirectory, "WriterPlugin");


            var ask1 = "Tomorrow is Valentine's day. I need to come up with a few date ideas. My significant other likes poems so write them in the form of a poem. Answer me in chinese.";
            var originalPlan = await planner.CreatePlanAsync(ask1);

            Console.WriteLine("Original plan:\n");
            Console.WriteLine(JsonSerializer.Serialize(originalPlan, new JsonSerializerOptions { WriteIndented = true }));

            string skPrompt = """
            {{$input}}

            Rewrite the above in the style of ..
            """;
            var shakespeareFunction = kernel.CreateSemanticFunction(skPrompt, "Shakespeare", "ShakespearePlugin", requestSettings: new OpenAIRequestSettings { MaxTokens = 2000, Temperature = 0.2, TopP = 0.5 });
           

            var ask = @"Tomorrow is Valentine's day. I need to come up with a few date ideas.
She likes Shakespeare so write using his style. Write them in the form of a poem. Answer me in chinese.";

            var newPlan = await planner.CreatePlanAsync(ask);

            Console.WriteLine("Updated plan:\n");
            Console.WriteLine(JsonSerializer.Serialize(newPlan, new JsonSerializerOptions { WriteIndented = true }));
            var originalPlanResult = await kernel.RunAsync(originalPlan);

            Console.WriteLine("Original Plan results:\n");
            Console.WriteLine(Utils.WordWrap(originalPlanResult.GetValue<string>(), 100));

            Thread.Sleep(60000);
            var newPlanResult = await kernel.RunAsync(newPlan);

            Console.WriteLine("New Plan results:\n");
            Console.WriteLine(newPlanResult.GetValue<string>());
            // Console.WriteLine(summary);
            return "";
        }
    }
}
